package site.yunnong.atvris.portal.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域问题
 * @author JinghaoZhang
 * @date 2021/5/30 20:58
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 允许所有主机发出跨域请求
        config.addAllowedOriginPattern("*"); // 高版本
//        config.addAllowedOrigin("*"); // 低版本
        //允许跨域发送Cookie
        // When allowCredentials is true,
        // allowedOrigins cannot contain the special value "*" since that
        // cannot be set on the "Access-Control-Allow-Origin" response header.
        // To allow credentials to a set of origins,
        // list them explicitly or consider using "allowedOriginPatterns" instead.
        config.setAllowCredentials(true);
        // 允许全部原始请求头
        config.addAllowedHeader("*");
        //允许所有请求方法跨域调用
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
